<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <!--
      <h4 class="title">若依后台管理系统</h4>
      <el-button
          size="middle"
          type="primary"
          style="width:45%;margin-bottom: 10px"
      >
        <div style="float: right;" >
          <router-link class="link-type" :to="'/username'">用户名密码</router-link>
        </div>
      </el-button>
      <el-button
          size="middle"
          type="primary"
          style="width:51%;margin-bottom: 10px"
      >
        <div style="float: right;" >
          <router-link class="link-type" :to="'/mobile'">手机验证码</router-link>
        </div>
      </el-button>
-->

      <h4 class="title">后台管理系统</h4>


      <el-button :type="getButtonType(loginForm.type,'username')" style="width:40%;margin-bottom: 10px" @click="changeType(1)" >
        用户名密码
<!--        <router-link class="link-type" :to="'/username'" style="width: 50%">用户名密码</router-link>-->
      </el-button>

      <el-button :type="getButtonType(loginForm.type,'mobile')" style="width:56%;margin-bottom: 10px" @click="changeType(2)" >
        手机验证码
<!--        <router-link class="link-type" :to="'/mobile'" style="width: 50%" @click="$event">手机验证码</router-link>-->
      </el-button>

      <el-form-item prop="username" v-if="loginForm.type === 1" label="用户名：">
        <el-input
            v-model="loginForm.username"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="账号"
        >
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password" v-if="loginForm.type === 1" label="密&nbsp&nbsp&nbsp码：">
        <el-input
            v-model="loginForm.password"
            type="password"
            size="large"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>

<!-- 手机号 验证码 -->

      <el-form-item label="手机号：" prop="mobile" v-if="loginForm.type === 2">
        <el-input  @keyup.enter="handleLogin" v-model="loginForm.mobile" placeholder="手机号">
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
          </el-input>
      </el-form-item>


      <el-form-item label="验证码：" v-if="loginForm.type === 2" prop="mobileCode">
        <el-input v-model="loginForm.mobileCode" @keyup.enter="handleLogin" placeholder="验证码">
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
          <template #suffix>
            <div v-if="messageCodeVis" class="second-text">{{countdown}}秒后重新获取</div>
            <el-button v-else type="primary" link @click="getCodeByMobile">获取验证码</el-button>
          </template>
        </el-input>
      </el-form-item>

<!--  单点登录    -->

      <el-form-item>
          <div style="width: 33%;text-align: center">
            <a href="https://gitee.com/oauth/authorize?client_id=c6c6d2cfc5e5a9b4cc5a67ffe58b3c93c2aeeda6355c39a7371aec20730f0cb0&redirect_uri=http://localhost/username&response_type=code">
              <img style="width: 40px;height: 40px;" src="/src/assets/icons/gitee.ico" alt="gitee单点图标">
            </a>
          </div>
        <div style="width: 33%;text-align: center">
          <a href="https://gitee.com/oauth/authorize?client_id=c6c6d2cfc5e5a9b4cc5a67ffe58b3c93c2aeeda6355c39a7371aec20730f0cb0&redirect_uri=http://127.0.0.1:8080/login/oauth&response_type=code">
            <img style="width: 40px;height: 40px;" src="/src/assets/icons/gitee.ico" alt="gitee单点图标">
          </a>
        </div>
        <div style="width: 33%;text-align: center">
          <a href="https://gitee.com/oauth/authorize?client_id=c6c6d2cfc5e5a9b4cc5a67ffe58b3c93c2aeeda6355c39a7371aec20730f0cb0&redirect_uri=http://127.0.0.1:8080/login/oauth&response_type=code">
            <img style="width: 40px;height: 40px;" src="/src/assets/icons/gitee.ico" alt="gitee单点图标">
          </a>
        </div>

      </el-form-item>

      <!--  单点登录    -->

<!--  手机号 验证码    -->

<!-- 图片验证码 -->
<!--      <el-form-item prop="code" v-if="captchaEnabled && loginForm.type === 1" label="验证码：">-->
<!--        <el-input-->
<!--            v-model="loginForm.code"-->
<!--            size="large"-->
<!--            auto-complete="off"-->
<!--            placeholder="验证码"-->
<!--            style="width: 63%"-->
<!--            @keyup.enter="handleLogin"-->
<!--        >-->
<!--          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>-->
<!--        </el-input>-->

<!--        <div class="login-code" v-if="loginForm.type === 1">-->
<!--          <img :src="codeUrl" @click="getCodeByImg" class="login-code-img"/>-->
<!--        </div>-->
<!--        <div class="login-code" v-else>-->
<!--          <el-button-->
<!--              size="large"-->
<!--              type="primary"-->
<!--              style="width:100%;margin-left: 10px"-->
<!--          >-->
<!--            <span >获取验证码</span>-->
<!--          </el-button>-->

<!--&lt;!&ndash;          <img :src="codeUrl" @click="getCode" class="login-code-img"/>&ndash;&gt;-->
<!--        </div>-->
<!--      </el-form-item>-->
      <!-- 图片验证码 -->


<!--      <el-checkbox v-if="loginForm.type === 1" v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>-->


      <el-form-item style="width:100%;">
        <el-button
            :loading="loading"
            size="large"
            type="primary"
            style="width:100%;"
            @click.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
<!--        <div style="float: right;" v-if="register">-->
<!--          <router-link class="link-type" :to="'/register'">立即注册</router-link>-->
<!--        </div>-->

      </el-form-item>

    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2024 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup>
// import
import { getCodeImg } from "@/api/login";
import { getMobileCode } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user';
import {RouterLink} from 'vue-router';
import { ref,onActivated } from 'vue'
import { ElMessage } from 'element-plus';
import axios from 'axios'

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
  mobileCode: [{ required: true, trigger: "change", message: "请输入手机验证码" }],
  mobile: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
};
const activeClass = ref("success");
const normalClass = ref("normal");
const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
// const register = ref(false);
const redirect = ref(undefined);

const messageCodeVis = ref(false)
let countdown = ref(0)

const loginForm = ref({
  username: "",
  password: "",
  mobile: "18438605001",
  mobileCode: "",
  rememberMe: false,
  code: "",
  uuid: "",
  type: 1 // 1：用户名密码 2：手机验证码
});



async function loginOauth1(){
  console.log('单点登录')
  const res = await axios.get('http://localhost:8080/login/oauth')
  console.log(res)
}

function loginOauth(){
  const code = route.query.code;
  console.log('code', code)
  if (code !== undefined){
    loading.value = true;
    userStore.loginOauth(code).then(() => {

      const query = route.query;
      console.log('query',query)
      const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
      router.push({ path: redirect.value || "/", query: otherQueryParams });
    }).catch(() => {
      loading.value = false;
      //用户名密码登陆失败后, 重新获取验证码
      if (captchaEnabled.value && loginForm.value.type === 1) {
        getCodeByImg();
      }
    });
  }
}

function sendCode(){
  const reg = /^1[3456789]\d{9}$/;
  if(!loginForm.value.mobile) return ElMessage.error('请输入手机号码')
  if (!reg.test(loginForm.value.mobile)) return
  countdown.value = 60
  messageCodeVis.value = true
  startCountdown()
}
/* 倒计时 */
const startCountdown = () => {
  const intervalId = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(intervalId)
      messageCodeVis.value = false
    }
  }, 1000)
}
//  手机号 验证码


watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码

      if (loginForm.value.type === 1){
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
      }

      // if (loginForm.value.rememberMe) {
      //   Cookies.set("username", loginForm.value.username, { expires: 30 });
      //   Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
      //   Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      // } else {
      //   // 否则移除
      //   Cookies.remove("username");
      //   Cookies.remove("password");
      //   Cookies.remove("rememberMe");
      // }
      // 调用action的登录方法

      userStore.login(loginForm.value).then(() => {

        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        router.push({ path: redirect.value || "/", query: otherQueryParams });
      }).catch(() => {
        loading.value = false;
        //用户名密码登陆失败后, 重新获取验证码
        if (captchaEnabled.value && loginForm.value.type === 1) {
          getCodeByImg();
        }
      });
    }
  });
}


function getButtonType(type,loginWay){
  if ((1===type && "username" === loginWay) || (2===type && "mobile" === loginWay)){
    return "success"
  } else {
    return "info"
  }
}

/*
    切换登录方式
 */
function changeType(value){
console.log('信息',loginForm.value.username,loginForm.value.password)

  if (value === 2){

    if (loginForm.value.username !== undefined) Cookies.set("username", loginForm.value.username, { expires: 30 });
    if (loginForm.value.password !== undefined) Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
    loginForm.value.username = undefined;
    loginForm.value.password = undefined;
    const mobile = Cookies.get("mobile");
    loginForm.value.mobile =  mobile === undefined ? loginForm.value.mobile : mobile;
  }

  if (value === 1){
    if (loginForm.value.mobile !== undefined) Cookies.set("mobile", loginForm.value.mobile, { expires: 30 });
    loginForm.value.mobile = undefined;
    loginForm.value.mobileCode = undefined;
    const username = Cookies.get("username");
    const password = Cookies.get("password");
    loginForm.value.username =  username === undefined ? loginForm.value.username : username;
    loginForm.value.password = password === undefined ? loginForm.value.password : decrypt(password);
    getCodeByImg()
  }

  loginForm.value.type = value;
}

function getCodeByImg() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCodeByMobile() {

  const reg = /^1[3456789]\d{9}$/;
  // console.log("@@" + loginForm.value.mobile.match(reg))
  if(!loginForm.value.mobile) return ElMessage.error('请输入手机号码')
  if (loginForm.value.mobile.match(reg) === null) return ElMessage.error('请输入有效手机号')
  if (!reg.test(loginForm.value.mobile)) return
  countdown.value = 10

  getMobileCode(loginForm.value.mobile).then(res => {

    if (res.uuid !== undefined) loginForm.value.uuid = res.uuid;
    messageCodeVis.value = true
    console.log('手机验证码：', res.data)
    startCountdown()
    if (res.msg !== null){
      return ElMessage.success(res.msg)
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  console.log('cookie: ',username,password,rememberMe)

  loginForm.value.username =  username === undefined ? loginForm.value.username : username;
  loginForm.value.password = password === undefined ? loginForm.value.password : decrypt(password);
  loginForm.value.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe)

  // console.log(loginForm.value)
  // loginForm.value = {
  //   username: username === undefined ? loginForm.value.username : username,
  //   password: password === undefined ? loginForm.value.password : decrypt(password),
  //   rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  // };
}


loginOauth()
getCodeByImg();
getCookie();
</script>

<style lang='scss' scoped>
.custom-icon-button {
  position: relative;
  padding-left: 27px; /* 确保有足够的空间放置图标 */
}

.custom-icon {
  position: absolute;
  left: 1px;
  top: 50%; /* 将图标垂直居中 */
  transform: translateY(-50%);
  width: 40px; /* 或者您的图标大小 */
  height: 40px; /* 或者您的图标大小 */
  background-image: url('src/assets/icons/gitee.ico');
  background-size: cover; /* 确保图标覆盖整个图标区域 */
}
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 20px auto;
  text-align: center;
  color: #707070;
}
.login-way {
  margin: 0px auto 20px auto;
  text-align: center;
  color: #707070;
}
.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}
.activeClass{
  color: #1ab394;
}
</style>
